<!--收货-->
<template>
	<div class="page-container">
		<page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
		<el-form class="flex_col flex_cell" :model="form" ref="form">
			<ex_super_table_page v-bind="option" ref="SuperTablePage" :autoLoad="false">
				<template v-slot:table-top>
					<el-alert
						v-if="isAutomaticWarehouseArea == 'Y'"
						:title="
							$tt('label_inbound_order_will_into_auto_location', {
								order: receivingCode,
							})
						"
						type="warning"
						:closable="false"
					/>
				</template>
				<template v-slot:type>
					<el-form-item :label="$tt('label_receiving_type')">
						<ex_super_input v-model="type" type="select" :items="typeList" i18n :disabled="typeDisabled"></ex_super_input>
					</el-form-item>
				</template>
				<!-- <template v-slot:table-top v-if="form.receivingBoxInput">
          <el-form-item :label="$t('label_receiving_box_number')" prop="receivingBoxCount">
            <el-input-number v-model="form.receivingBoxCount" :min="0" :max="9999" step-strictly
              :disabled="orderEditDisabled" />
          </el-form-item>
        </template> -->
			</ex_super_table_page>
		</el-form>
		<ex_super_dialog_form
			ref="formDialogReceiving"
			:title="$tt('label_receiving_confirm')"
			v-bind="dialogReceivingBind"
			@afterSubmitSuccess="receivingSuccess"
		>
			<template v-slot:temporaryAreaId="{ formData }">
				<el-form-item :label="$tt('label_inbound_warehouse_area')" prop="temporaryAreaId" class="form_item_mini">
					<base_area_select
						:value="formData.temporaryAreaId"
						:warehouseId="$loginUser.currentWarehouseId"
						@changeItem="(e) => changeArea(e, formData)"
						class="form_input_small"
					/>
				</el-form-item>
			</template>
			<template v-slot:temporaryLocationId="{ formData }">
				<el-form-item :label="$tt('label_inbound_warehouse_location')" prop="temporaryLocationId" class="form_item_mini">
					<base_location_select
						v-model="formData.temporaryLocationId"
						:areaId="formData.temporaryAreaId"
						@changeItem="(e) => (e ? (formData.temporaryLocationCode = e.code) : null)"
						class="form_input_small"
					/>
				</el-form-item>
			</template>
			<template v-slot:receivingUserId="{ formData }">
				<el-form-item :label="$tt('label_receiving_user')" prop="receivingUserId" class="form_item_mini">
					<ex_super_input
						:value="formData.receivingUserId"
						type="select"
						storeData
						class="form_input_small"
						url="/ums-api/user/UserInfoRpc/getUserDict.json"
						:option="{ label: 'userName', value: 'userId' }"
						:clearable="false"
						@changeItem="(e) => changeReceivingUser(e, formData)"
					/>
				</el-form-item>
			</template>
			<template v-slot:dialog_bottom>
				<div class="flex_row_center card margin-small">
					<i class="el-icon-warning color_warning el-icon--left icon-small" />
					<p>{{ $tt('text_receiving_confirm_tip_info') }}</p>
				</div>
			</template>
		</ex_super_dialog_form>
		<report_anomaly
			ref="report_anomaly"
			:orderTypeList="$enumOptions['AbnormalOrderTypeEnum'].filter((it) => it == 'INBOUND')"
			@success="reload()"
			system="WMS"
		/>
	</div>
</template>
<script>
import report_anomaly from '@/component/dialog/report_anomaly.vue';
import volume_input from '@/component/wms/volume_input.vue';

import superTablePageFunction from '@/mixin/super-table-page-function';
import router_params from '@/mixin/router_params';
import page_table_model_manage from '@/mixin/page_table_model_manage';

export default {
	title: 'title_transfer_receiving',
	mixins: [superTablePageFunction, router_params, page_table_model_manage],
	components: { volume_input, report_anomaly },

	data() {
		return {
			type: 'BOX',
			typeDisabled: false,

			receivingId: '',
			receivingCode: '',
			isPallet: 'N',
			isAutomaticWarehouseArea: 'N',

			customerId: '',
			customerCode: '',
			customerName: '',

			orderEditDisabled: false,
			form: {
				receivingBoxInput: false,
				list: [],
			},

			option: {
				search: {
					default: { code: '' },
					model: [
						{ label: 'label_receiving_type', slot: 'type' },
						{ label: '', key: 'code', keylist: [{ label: 'label_inbound_code', value: 'code' }] },
					],
				},
				actionExtra: [
					{
						label: 'label_report_exception',
						attrs: { icon: 'el-icon-plus', type: 'primary' },
						auth: 'wms_anomaly_report',
						click: () => {
							let data = { orderType: 'INBOUND' };
							if (this.receivingCode) {
								data.customerId = this.customerId;
								data.customerCode = this.customerCode;
								data.customerName = this.customerName;
								data.orderNo = this.receivingCode;
							}
							this['$refs']['report_anomaly'].showNew({
								formDisabled: !!this.receivingCode,
								data,
								onlySetData: true,
							});
						},
					},
					{
						label: 'label_receiving_confirm',
						attrs: { type: 'primary' },
						if: () => !this.orderEditDisabled,
						click: this.clickReceiving,
					},
					// { label: 'label_print_inbound_code', attrs: { type: "primary" }, click: this.$noFunction },
					// { label: 'label_batch_import', click: this.$noFunction },
					// { label: 'label_batch_measure', click: this.$noFunction },
					// { label: 'label_no_arrival_sku', attrs: { type: "danger" }, click: this.$noFunction },
				],
				table: {
					autoPage: false,
					specialStyle: false,
					attrs: { 'cell-class-name': this.cellClassName, 'span-method': this.objectSpanMethod },
					url: '/wms-api/inbound/WmsInboundTransitReceivingDetailRpc/selectBoxDetail.json',
					urlDataHandle: this.dataHandle,
					model: this.init_table_model(),
				},
			},
			formRules: {
				measureWeight: {
					required: true,
					trigger: 'blur',
					validator: (r, v, cb) => {
						if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 3, 9)) {
							return cb(this.$tt('tip_only_digit_int_length', { digit: 3, int: 9 }));
						}
						cb();
					},
				},
				measureVolume: {
					required: true,
					trigger: 'blur',
					validator: (r, v, cb) => {
						if (!_.isEmpty(v)) {
							if (Number.isNaN(v)) {
								return cb(this.$tt('tip_lwh_use_split'));
							} else if (!this.$reg.DigitNumber(v, 6, 9)) {
								return cb(this.$tt('tip_only_digit_int_length', { digit: 6, int: 9 }));
							}
						}
						cb();
					},
				},
			},
			skuUrlList: [],
			dialogReceivingBind: {
				customClass: 'dialog_auto',
				submitUrl: '/wms-api/inbound/WmsInboundTransitReceivingDetailRpc/receiving.json',
				submitDataHandle: this.submitReceivingDataHandle,
				form: {
					itemClass: 'form_item_mini',
					inputClass: 'form_input_small ',
					formClass: 'form_mini_col2',
					inline: true,
					model: [
						{ key: 'receivingCode', label: 'label_inbound_code', formType: 'text', inputClass: 'bold ', itemClass: 'form_item_default' },
						{
							key: 'planBoxNumber',
							label: 'label_plan_receiving_box_number',
							formType: 'text',
							inputClass: 'bold ',
							formatter: (r, c, v) => v || this.$tt('data_temp_none'),
						},
						{ key: 'planPieceNumber', label: 'label_plan_receiving_number', formType: 'text', inputClass: 'bold ' },
						{ key: 'actualBoxNumber', label: 'label_actual_receiving_box_number', formType: 'text', inputClass: 'bold ' },
						{ key: 'actualPieceNumber', label: 'label_actual_receiving_number', formType: 'text', inputClass: 'bold ' },
						{ key: 'temporaryAreaId', slot: 'temporaryAreaId' },
						{ key: 'temporaryLocationId', slot: 'temporaryLocationId' },
						{ key: 'receivingUserId', slot: 'receivingUserId' },
					],
					rules: {
						receivingUserId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
						temporaryAreaId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
					},
				},
			},
		};
	},

	computed: {
		typeSku: function() {
			return this.type == 'SKU';
		},
		typeBox: function() {
			return this.type == 'BOX';
		},
		typePallet: function() {
			return this.type == 'PALLET';
		},
		Pallet: function() {
			return this.isPallet == 'Y';
		},

		typeList() {
			if (this.Pallet) {
				return [{ _label: 'Receiving_PALLET', _value: 'PALLET' }];
			} else {
				return [
					{ _label: 'Receiving_BOX', _value: 'BOX' },
					{ _label: 'Receiving_SKU', _value: 'SKU' },
				];
			}
		},
	},

	methods: {
		option_table_model() {
			return [
				// { key: 'boxNumber', label: 'label_box_order_number', 'width': 100, 'show-overflow-tooltip': true, },
				{
					key: 'palletNo',
					label: 'label_pallet_code',
					'min-width': 140,
					'show-overflow-tooltip': true,
					if: () => this.typePallet,
				},

				{ key: 'boxNo', label: 'label_box_code', 'min-width': 140, 'show-overflow-tooltip': true },
				{ key: 'skuBarcode', label: 'label_sku_code', 'min-width': 120, 'show-overflow-tooltip': true },
				{ key: 'skuName', label: 'label_sku_name', 'min-width': 120, 'show-overflow-tooltip': true },
				{
					key: 'skuUrl',
					label: 'label_sku_image',
					width: 120,
					render: (h, { row }) => <ex_image_view class="page_table_image" src={row.skuUrl} lazy fit="fill" preview-src-list={this.skuUrlList} />,
				},
				{
					key: 'receivingStatus',
					label: 'label_receiving_status',
					'show-overflow-tooltip': true,
					width: 100,
					formatter: (r, c, v, i) => this.$enumShow(v, 'ReceivingStatusEnum'),
				},
				{
					key: 'checkoutStatus',
					label: 'label_checkout_staus',
					'show-overflow-tooltip': true,
					width: 100,
					formatter: (r, c, v, i) => this.$enumShow(v, 'CheckoutStatusEnum'),
				},
				// { key: 'quantityBox', label: 'label_plan_receiving_box_number', 'width': 100, },
				{
					key: 'receivingPallet',
					label: 'label_actual_receiving_pallet_number',
					'min-width': 180,
					keyShowForce: [true],
					if: () => this.typePallet,
					render: (h, { column, row, index }) => {
						const item = row[column.property];
						if (!this.typePallet || this.disabledEdit(row)) {
							return item;
						}
						return (
							<el-form-item prop={`list.${index}.${column.property}`}>
								<el-input-number
									value={item}
									class="w_fill"
									min={0}
									max={1}
									onInput={(value) => {
										this.changeReceivingPallet(value, row);
									}}
									placeholder={column.label}
								></el-input-number>
							</el-form-item>
						);
					},
				},
				{
					key: 'receivingBox',
					label: 'label_actual_receiving_box_number',
					'min-width': 180,
					keyShowForce: [true],
					if: () => !this.typePallet,
					render: (h, { column, row, index }) => {
						const item = row[column.property];
						if (!this.typeBox || this.disabledEdit(row)) {
							return row.receivingBoxQty;
						}
						const min = this.form.receivingBoxInput ? 1 : 0;
						const max = this.form.receivingBoxInput ? 999 : 1;
						return (
							<el-form-item prop={`list.${index}.${column.property}`}>
								<el-input-number
									value={item}
									class="w_fill"
									min={min}
									max={max}
									onInput={(value) => {
										this.changeReceivingBox(value, row);
									}}
									placeholder={column.label}
								></el-input-number>
							</el-form-item>
						);
					},
				},
				{ key: 'quantity', label: 'label_plan_receiving_number', width: 100 },
				{
					key: 'receivingQty',
					label: 'label_actual_receiving_number',
					'min-width': 180,
					keyShowForce: [true],
					render: (h, { column, row, index }) => {
						if (!this.typeSku || this.disabledEdit(row)) {
							return row.receivingQty;
						}
						return (
							<el-form-item prop={`list.${index}.${column.property}`}>
								<el-input-number
									value={row.receivingQty}
									class="w_fill"
									min={0}
									max={row.quantity}
									onInput={(value) => {
										this.changeReceivingQty(value, row);
									}}
									placeholder={column.label}
								></el-input-number>
							</el-form-item>
						);
					},
				},
				// {
				//     key: 'isAutomaticWarehouseArea', label: 'label_is_auto_location', 'width': 110, 'show-overflow-tooltip': true,
				//     formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum")
				//   },
			];
		},
		changeReceivingUser(user, data) {
			if (!user) user = { userId: null, userCode: null, userName: null };
			data.receivingUserId = user.userId;
			data.receivingUserCode = user.userCode;
			data.receivingUserName = user.userName;
		},

		changeArea(it, data) {
			if (!it) it = { code: null, id: null };
			data.temporaryAreaCode = it.code;
			data.temporaryAreaId = it.id;
		},

		//修改收货箱数，需要同时对对象内连接的其他箱子进行操作
		changeReceivingPallet(e, row) {
			row._linkPallet.forEach((it) => {
				it.receivingBox = e;
				it.receivingPallet = e;
				it.receivingQty = e ? it.quantity : 0;
			});
		},
		changeReceivingBox(e, row) {
			row._linkBox.forEach((it) => {
				it.receivingBox = e;
				it.receivingQty = e ? it.quantity : 0;
			});
			if (row._linkPallet) {
				const _pallet = row._linkPallet.some((it) => it.receivingQty);
				row._linkPallet.forEach((it) => {
					it.receivingPallet = _pallet ? 1 : 0;
				});
			}
		},
		changeReceivingQty(e, row) {
			row.receivingQty = e;
			const _box = row._linkBox.some((it) => it.receivingQty);
			row._linkBox.forEach((it) => {
				it.receivingBox = _box ? 1 : 0;
			});
			if (row._linkPallet) {
				const _pallet = row._linkPallet.some((it) => it.receivingQty);
				row._linkPallet.forEach((it) => {
					it.receivingPallet = _pallet ? 1 : 0;
				});
			}
		},
		init_data_default(into_params) {
			let params = into_params;
			let search = params;
			if (!_.isEmpty(search)) {
				this.receivingId = '';
				this.receivingCode = '';
				this.$refs['SuperTablePage'].setSearchData(Object.assign({}, this.$refs['SuperTablePage'].getSearchData(), search));

				let _keys = Object.keys(search);
				this.option.search.model.forEach((it) => {
					if (it.keylist) {
						let _new_key = _.head(
							_.intersection(
								it.keylist.map((_k) => _k.value),
								_keys
							)
						);
						if (_new_key) it.key = _new_key;
					}
				});
				this.$nextTick(() => {
					this.$refs['SuperTablePage'].loadDataForSearch();
				});
			}
		},
		isBoxReceiving(row) {
			return row.boxReceivingStatus == 'RECEIVING_COMPLETED';
		},
		isBoxCheckout(row) {
			return row.boxCheckoutStatus == 'CHECKOUT_COMPLETED';
		},
		isHasReceiving(row) {
			return row.receivingStatus == 'RECEIVING_COMPLETED';
		},
		isHasChekout(row) {
			return row.checkoutStatus == 'CHECKOUT_COMPLETED';
		},
		disabledEdit(row) {
			return this.isHasReceiving(row) || this.isHasChekout(row) || this.orderEditDisabled;
		},
		cellClassName({ row, column, rowIndex, columnIndex }) {
			if (this.disabledEdit(row)) {
				return 'tableCell_disabled';
			}
			return 'tableCell_noHoverLight';
		},
		objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			if (['boxNumber', 'boxNo', 'receivingBox', 'measureWeight', 'measureVolume'].includes(column.property)) {
				return { rowspan: row.rowspanBox, colspan: 1 };
			} else if (['receivingPallet', 'palletNo'].includes(column.property)) {
				return { rowspan: row.rowspanPallet, colspan: 1 };
			}
		},
		dataHandle(res) {
			if (!res.data || !res.data.receivingCode) {
				this.$message.warning(this.$tt('tip_search_no_data'));
				this.form.list = [];
				return [];
			}
			const noBoxCode = res.data.boxIsEmpty == 'Y' && !_.isEmpty(res.data.inboundOrderSkuList);

			const _list = noBoxCode ? res.data.inboundOrderSkuList : res.data.boxDetailList;

			if (_.isEmpty(_list)) {
				this.$message.warning(this.$tt('tip_search_no_data'));
				this.form.list = [];
				return [];
			}
			this.receivingCode = res.data.receivingCode;
			this.receivingId = res.data.receivingId;
			this.isPallet = res.data.isPallet;
			this.isAutomaticWarehouseArea = res.data.isAutomaticWarehouseArea;
			this.customerId = res.data.customerId;
			this.customerCode = res.data.customerCode;
			this.customerName = res.data.customerName;
			this.form.receivingBoxInput = false;

			this.orderEditDisabled = _list.some((it) => this.isHasReceiving(it));
			this.typeDisabled = true;
			if (noBoxCode) {
				_list.forEach((it) => (it.boxDetailId = it.id));
				this.form.receivingBoxInput = true;
				this.type = 'BOX';
			} else if (this.Pallet) {
				this.type = 'PALLET';
			} else {
				this.type = 'BOX';
			}
			this.skuUrlList = _list.map((it) => it.skuUrl);

			_list
				.sort((a, b) => {
					if (this.Pallet) {
						if (a.palletNo == b.palletNo) {
						} else if (a.palletNo > b.palletNo) {
							return 1;
						} else if (a.palletNo < b.palletNo) {
							return -1;
						}
					}
					if (a.boxNo == b.boxNo) {
						return 0;
					} else if (a.boxNo > b.boxNo) {
						return 1;
					} else if (a.boxNo < b.boxNo) {
						return -1;
					}
				})
				.map((it, i) => {
					it._linkBox = _list.filter((it2) => it2.boxNo == it.boxNo);
					if (it.rowspanBox == undefined) {
						it._linkBox.forEach((it2) => (it2.rowspanBox = 0));
						it.rowspanBox = it._linkBox.length;
					}
					if (this.Pallet) {
						it._linkPallet = _list.filter((it2) => it2.palletNo == it.palletNo);
						if (it.rowspanPallet == undefined) {
							it._linkPallet.forEach((it2) => (it2.rowspanPallet = 0));
							it.rowspanPallet = it._linkPallet.length;
						}
					}

					if (this.disabledEdit(it)) {
						it.receivingBox = this.isBoxReceiving(it) ? 1 : 0;
						if (it._linkPallet) it.receivingPallet = it._linkPallet.some((it) => this.isBoxReceiving(it)) ? 1 : 0;
					} else {
						it.receivingPallet = 1;
						it.receivingBox = 1;
						it.receivingQty = it.quantity;
						it.measureVolume = null;
						it.measureWeight = null;
					}
				});
			this.refresh_table_visible();
			this.form.list = _list;
			return _list;
		},
		clickReceiving() {
			if (_.isEmpty(this.receivingCode)) {
				return this.$message.error(this.$tt('tip_please_first_search'));
			}
			this.$refs.form.validate((valid) => {
				if (valid) {
					let _hasList = this.$refs['SuperTablePage'].getData();
					if (_hasList.some((it) => this.disabledEdit(it))) {
						return this.$message.error(this.$tt('tip_transfer_order_has_receiving'));
					}
					_hasList = _hasList.filter((it) => !this.disabledEdit(it));

					// let groupList = _.groupBy(_hasList, 'boxNo')
					// _.forOwn(groupList, (v, k) => {
					//   let hasW = _.find(v, sku => sku.measureWeight)
					//   if (hasW != null) {
					//     v.forEach(sku => this.$set(sku, "measureWeight", hasW.measureWeight))
					//   }
					//   let hasV = _.find(v, sku => sku.measureVolume)
					//   if (hasV != null) {
					//     v.forEach(sku => this.$set(sku, "measureVolume", hasV.measureVolume))
					//   }
					// })

					let _list = _hasList.filter((it) => it.receivingQty);
					if (this.form.receivingBoxInput) {
						_list = _hasList;
					}
					let planBoxNumber = _.uniqBy(_hasList, 'boxNo').length;
					let actualBoxNumber = _.uniqBy(_list, 'boxNo').length;
					if (this.form.receivingBoxInput) {
						planBoxNumber = '';
						actualBoxNumber = _.head(_list).receivingBox;
					}

					let _receivingQty = _.reduce(_list, (sum, it) => sum + it.receivingQty, 0);
					if (_receivingQty == 0) return this.$message.error(this.$tt('tip_receiving_content_no_empty'));

					let user = this.$loginUser;
					this.$refs.formDialogReceiving.show(
						{
							receivingId: this.receivingId,
							receivingCode: this.receivingCode,
							receivingType: this.type,
							receivingBoxInput: this.form.receivingBoxInput,
							planBoxNumber: planBoxNumber,
							planPieceNumber: _.reduce(_hasList, (sum, v) => sum + v.quantity, 0),
							actualBoxNumber: actualBoxNumber,
							actualPieceNumber: _receivingQty,
							temporaryAreaId: null,
							temporaryLocationId: null,
							receivingUserId: user.userId,
							receivingUserCode: user.userCode,
							receivingUserName: user.userName,
							items: _list,
						},
						true
					);
				} else {
					this.$message.error(this.$t('form_validate_error'));
					return false;
				}
			});

			return;
		},
		submitReceivingDataHandle(data) {
			let _list = data.items.map((it) => {
				return {
					boxId: it.boxId,
					receivingType: data.receivingType,
					boxDetailId: it.boxDetailId,
					receivingQty: it.receivingQty,
					temporaryAreaId: data.temporaryAreaId,
					temporaryAreaCode: data.temporaryAreaCode,
					temporaryLocationId: data.temporaryLocationId,
					temporaryLocationCode: data.temporaryLocationCode,
					receivingUserId: data.receivingUserId,
					receivingUserCode: data.receivingUserCode,
					receivingUserName: data.receivingUserName,
					measureWeight: it.measureWeight,
					measureVolume: it.measureVolume,
				};
			});
			let out = {
				receivingId: data.receivingId,
				receivingType: data.receivingType,

				boxDetailList: _list,
			};
			if (data.receivingBoxInput) {
				out.noBoxDetail = {
					receivingBoxQty: data.actualBoxNumber,
				};
			}
			return out;
		},
		receivingSuccess() {
			this.reload();
			this.$emitPage('transfer=>checkout_list', 'reload');
			this.$emitPage('transfer=>receiving_list', 'reload');
		},
	},
};
</script>
<style scoped></style>
